from re import match

from django.contrib.auth.backends import ModelBackend
from itsdangerous import SignatureExpired, TimedJSONWebSignatureSerializer
from meiduo_mall.settings import SECRET_KEY

from apps.users.models import User


def get_object_by_username(username):
    try:
        # 通过正则区分用户名和手机号，并获取对象
        if match(r'1[3-9]\d{9}', username):
            user = User.objects.get(mobile=username)
        else:
            user = User.objects.get(username=username)
    except User.DoesNotExist:
        return None
    else:
        return user


class UsernameMoblieModelBackend(ModelBackend):
    """自定义验证后端"""

    def authenticate(self, request, username=None, password=None, **kwargs):
        user = get_object_by_username(username)
        # 判断密码是否正确
        if user is not None and user.check_password(password):
            return user
        else:
            return None


def activate_email_url(email, userid):
    """
    生成加密的邮件激活url
    :param email:需要激活的邮箱
    :param userid:用户的ID
    """
    # 创建序列化器实例
    s = TimedJSONWebSignatureSerializer(secret_key=SECRET_KEY, expires_in=3600)
    # 组织数据
    data = {
        'email': email,
        'userid': userid
    }
    # 加密数据
    token = s.dumps(data)
    # 返回激活邮件的url
    return 'http://www.meiduo.site:8000/activate_email/?%s' % token


def check_email_activate_token(token):
    """解密并返回用户对象"""
    s = TimedJSONWebSignatureSerializer(secret_key=SECRET_KEY, expires_in=3600)
    try:
        result = s.loads(token)
    except SignatureExpired:
        return None
    email = result.get('email')
    userid = result.get('userid')
    try:
        user = User.objects.get(id=userid, email=email)
    except User.DoesNotExist:
        return None
    else:
        return user
